import React, { lazy } from "react";
import {
  BrowserRouter,
  useLocation,
  useRoutes,
  Navigate,
} from "react-router-dom";
const Home = lazy(() => import("../pages/home"));
const Layout = lazy(() => import("../pages/layout"));
const UserUpload = lazy(() => import("../pages/userUpload"));
const Login = lazy(() => import("../pages/login"));
const Detail = lazy(() => import('../pages/detail'))
const Car = lazy(() => import('../pages/car'))
interface PropsType {
  children: any;
}

const PriviteRouter: React.FC<PropsType> = ({ children }) => {
  const token = localStorage.getItem("token");
  const location = useLocation();
  const { pathname } = location;

  // 是否登录
  if (token) {
    // 已经登录
    if (pathname === "/login") {
      // 已经登录 访问登录页面
      return <Navigate to="/"></Navigate>;
    } else {
      // 已经登录 访问非登录页面
      return children;
    }
  } else {
    // 未登录
    if (pathname === "/login") {
      return children;
    } else {
      return <Navigate to="/login"></Navigate>;
    }
  }
};

const routes = [
  {
    element: (
      <PriviteRouter>
        <Layout></Layout>
      </PriviteRouter>
    ),
    path: "/",
    children: [
      {
        element: <Home></Home>,
        path: "/",
      },
      {
        element: <Car></Car>,
        path: "/car",
      },
    ],
  },
  {
    element: (
      <PriviteRouter>
        <UserUpload></UserUpload>
      </PriviteRouter>
    ),
    path: "/user/upload",
  },
  {
    element: (
      <PriviteRouter>
        <Detail></Detail>
      </PriviteRouter>
    ),
    path: "/detail/:id",
  },
  {
    element: <Login></Login>,
    path: "/login",
  },
];

const Router = () => {
  const App = () => useRoutes(routes);
  return (
    <BrowserRouter>
      <App></App>
    </BrowserRouter>
  );
};

export default Router;
